package team.paimengshop.show;

import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import team.paimengshop.server_database.UserInfoOperate;
import team.paimengshop.server_dataclass.Commodity;
import team.paimengshop.server_dataclass.Order;
import team.paimengshop.server_dataclass.User;

import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;

public class userViewController implements Initializable
{
    private final TableView<Person> table = new TableView<>();
    private final ObservableList<Person> data =
            FXCollections.observableArrayList();

    @FXML
    private AnchorPane userPane;

    @FXML
    private TextField textInput1;
    @FXML
    private TextField textInput2;
    @FXML
    private TextField textInput3;

    @FXML
    private Button button1;
    @FXML
    private Button button2;
    @FXML
    private Button button3;

    private ArrayList<Integer> idList;

    private ArrayList<String> userNameList;

    private ArrayList<String> emailList;

    private ArrayList<User> userArrayList;

    private TableColumn idCol;

    private TableColumn userNameCol;

    private TableColumn passwordCol;

    private TableColumn emailCol;

    private TableColumn headImageURLCol;

    private TableColumn cartCol;

    private TableColumn collectionCol;


    @Override
    public void initialize(URL url, ResourceBundle resourceBundle)
    {
//        data.remove(0);
        userArrayList = UserInfoOperate.GetAllUser();
        for(int i = 0; i < userArrayList.size(); i++)
        {
            User user = userArrayList.get(i);
            Person person = new Person(user.getId(), user.getUserName(), user.getEmail(), user.getPassword().replaceAll(".", "*"), user.getHeadImageURL(),
                    Commodity.commodityArrayListToString(user.getCart()), Commodity.commodityArrayListToString(user.getCollection()));
            data.add(person);
        }

        table.setEditable(true);

        idCol = new TableColumn("Id");
        idCol.setMinWidth(100);
        idCol.setCellValueFactory(
                new PropertyValueFactory<>("id"));

        userNameCol = new TableColumn("User Name");
        userNameCol.setMinWidth(100);
        userNameCol.setCellValueFactory(
                new PropertyValueFactory<>("userName"));
        userNameCol.setSortable(false);

        passwordCol = new TableColumn("Password");
        passwordCol.setMinWidth(200);
        passwordCol.setCellValueFactory(
                new PropertyValueFactory<>("password"));
        passwordCol.setSortable(false);


        emailCol = new TableColumn("Email");
        emailCol.setMinWidth(200);
        emailCol.setCellValueFactory(
                new PropertyValueFactory<>("email"));
        emailCol.setSortable(false);

        headImageURLCol = new TableColumn("HeadImageURL");
        headImageURLCol.setMinWidth(200);
        headImageURLCol.setCellValueFactory(
                new PropertyValueFactory<>("headImageURL"));

        cartCol = new TableColumn("Cart");
        cartCol.setMinWidth(200);
        cartCol.setCellValueFactory(
                new PropertyValueFactory<>("cart"));

        collectionCol = new TableColumn("Collection");
        collectionCol.setMinWidth(200);
        collectionCol.setCellValueFactory(
                new PropertyValueFactory<>("collection"));

        table.setPrefWidth(1200);
        table.setPrefHeight(550);
        table.setItems(data);
        table.getColumns().addAll(idCol, userNameCol, passwordCol,emailCol,headImageURLCol,cartCol,collectionCol);

        userPane.getChildren().add(table);

        idList = new ArrayList<>();
        for(int i = 0; i < userArrayList.size(); i++)
        {
            idList.add((Integer)idCol.getCellData(i));
        }
        userNameList = new ArrayList<>();
        for(int i = 0; i < userArrayList.size(); i++)
        {
            userNameList.add((String)userNameCol.getCellData(i));
        }
        emailList = new ArrayList<>();
        for(int i = 0; i < userArrayList.size(); i++)
        {
            emailList.add((String)emailCol.getCellData(i));
        }
    }

    public void Button1Clicked(ActionEvent actionEvent)
    {
        if(textInput1.getText().equals("") || textInput1.getText() == null)
        {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("查询");
            alert.setContentText("用户id不能为空！");
            alert.setHeaderText("查询失败");
            alert.showAndWait();
        }
        else
        {
            idCol.setSortType(TableColumn.SortType.ASCENDING);
            table.requestFocus();
            int index;
            try
            {
                index = BinarySearch(idList, Integer.parseInt(textInput1.getText()));
            }
            catch (NumberFormatException e)
            {
                index = -1;
            }
            if(index != -1)
            {
                table.getSelectionModel().select(index);
                table.scrollTo(index);
                textInput1.clear();
            }
            else
            {
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("查询");
                alert.setContentText("用户id不存在！");
                alert.setHeaderText("查询失败");
                alert.showAndWait();
                textInput1.clear();
            }
        }
    }

    public void Button2Clicked(ActionEvent actionEvent)
    {
        if(textInput2.getText().equals("") || textInput2.getText() == null)
        {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("查询");
            alert.setContentText("用户名不能为空！");
            alert.setHeaderText("查询失败");
            alert.showAndWait();
        }
        else
        {
            idCol.setSortType(TableColumn.SortType.ASCENDING);
            table.requestFocus();
            int index = -1;
            for(int i = 0; i < userNameList.size(); i++)
            {
                if(userNameList.get(i).equals(textInput2.getText()))
                {
                    index = i;
                    break;
                }
            }
            if(index != -1)
            {
                table.getSelectionModel().select(index);
                table.scrollTo(index);
                textInput2.clear();
            }
            else
            {
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("查询");
                alert.setContentText("用户名不存在！");
                alert.setHeaderText("查询失败");
                alert.showAndWait();
                textInput2.clear();
            }
        }
    }

    public void Button3Clicked(ActionEvent actionEvent)
    {
        if(textInput3.getText().equals("") || textInput3.getText() == null)
        {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("查询");
            alert.setContentText("用户邮箱不能为空！");
            alert.setHeaderText("查询失败");
            alert.showAndWait();
        }
        else
        {
            idCol.setSortType(TableColumn.SortType.ASCENDING);
            table.requestFocus();
            int index = -1;
            for(int i = 0; i < emailList.size(); i++)
            {
                if(emailList.get(i).equals(textInput3.getText()))
                {
                    index = i;
                    break;
                }
            }
            if(index != -1)
            {
                table.getSelectionModel().select(index);
                table.scrollTo(index);
                textInput3.clear();
            }
            else
            {
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("查询");
                alert.setContentText("用户邮箱不存在！");
                alert.setHeaderText("查询失败");
                alert.showAndWait();
                textInput3.clear();
            }
        }
    }

    public void Refresh(ActionEvent actionEvent)
    {
        data.clear();
        table.refresh();
        userArrayList.clear();
        userArrayList = UserInfoOperate.GetAllUser();
        for(int i = 0; i < userArrayList.size(); i++)
        {
            User user = userArrayList.get(i);
            Person person = new Person(user.getId(), user.getUserName(), user.getEmail(), user.getPassword().replaceAll(".", "*"), user.getHeadImageURL(),
                    Commodity.commodityArrayListToString(user.getCart()), Commodity.commodityArrayListToString(user.getCollection()));
            data.add(person);
        }

        table.setEditable(true);

        idCol = new TableColumn("Id");
        idCol.setMinWidth(100);
        idCol.setCellValueFactory(
                new PropertyValueFactory<>("id"));

        userNameCol = new TableColumn("User Name");
        userNameCol.setMinWidth(100);
        userNameCol.setCellValueFactory(
                new PropertyValueFactory<>("userName"));
        userNameCol.setSortable(false);

        passwordCol = new TableColumn("Password");
        passwordCol.setMinWidth(200);
        passwordCol.setCellValueFactory(
                new PropertyValueFactory<>("password"));
        passwordCol.setSortable(false);


        emailCol = new TableColumn("Email");
        emailCol.setMinWidth(200);
        emailCol.setCellValueFactory(
                new PropertyValueFactory<>("email"));
        emailCol.setSortable(false);

        headImageURLCol = new TableColumn("HeadImageURL");
        headImageURLCol.setMinWidth(200);
        headImageURLCol.setCellValueFactory(
                new PropertyValueFactory<>("headImageURL"));

        cartCol = new TableColumn("Cart");
        cartCol.setMinWidth(200);
        cartCol.setCellValueFactory(
                new PropertyValueFactory<>("cart"));

        collectionCol = new TableColumn("Collection");
        collectionCol.setMinWidth(200);
        collectionCol.setCellValueFactory(
                new PropertyValueFactory<>("collection"));

        table.setPrefWidth(1200);
        table.setPrefHeight(550);
        table.setItems(data);
        table.getColumns().addAll(idCol, userNameCol, passwordCol,emailCol,headImageURLCol,cartCol,collectionCol);

        idList = new ArrayList<>();
        for(int i = 0; i < userArrayList.size(); i++)
        {
            idList.add((Integer)idCol.getCellData(i));
        }
        userNameList = new ArrayList<>();
        for(int i = 0; i < userArrayList.size(); i++)
        {
            userNameList.add((String)userNameCol.getCellData(i));
        }
        emailList = new ArrayList<>();
        for(int i = 0; i < userArrayList.size(); i++)
        {
            emailList.add((String)emailCol.getCellData(i));
        }
    }

    public static class Person   //用户数据模板，用于绑定表格中的单元
    {
        private final SimpleIntegerProperty id;
        private final SimpleStringProperty userName;
        private final SimpleStringProperty password;
        private final SimpleStringProperty email;
        private final SimpleStringProperty headImageURL;
        private final SimpleStringProperty cart;
        private final SimpleStringProperty collection;

        private Person(int id,String userName, String email, String password,String headImageURL,String cart,String collection)

        {
            this.id = new SimpleIntegerProperty(id);
            this.userName = new SimpleStringProperty(userName);
            this.email = new SimpleStringProperty(email);
            this.password = new SimpleStringProperty(password);
            this.headImageURL = new SimpleStringProperty(headImageURL);
            this.cart = new SimpleStringProperty(cart);
            this.collection = new SimpleStringProperty(collection);
        }

        public String getUserName()
        {
            return userName.get();
        }

        public SimpleStringProperty userNameProperty()
        {
            return userName;
        }

        public void setUserName(String userName)
        {
            this.userName.set(userName);
        }

        public String getPassword()
        {
            return password.get();
        }

        public SimpleStringProperty passwordProperty()
        {
            return password;
        }

        public void setPassword(String password)
        {
            this.password.set(password);
        }

        public String getEmail() {
            return email.get();
        }

        public SimpleStringProperty emailProperty()
        {
            return email;
        }

        public void setEmail(String email)
        {
            this.email.set(email);
        }

        public String getHeadImageURL()
        {
            return headImageURL.get();
        }

        public SimpleStringProperty headImageURLProperty()
        {
            return headImageURL;
        }

        public void setHeadImageURL(String headImageURL)
        {
            this.headImageURL.set(headImageURL);
        }

        public String getCart() {
            return cart.get();
        }

        public SimpleStringProperty cartProperty()
        {
            return cart;
        }

        public void setCart(String cart)
        {
            this.cart.set(cart);
        }

        public String getCollection()
        {
            return collection.get();
        }

        public SimpleStringProperty collectionProperty()
        {
            return collection;
        }

        public void setCollection(String collection)
        {
            this.collection.set(collection);
        }

        public int getId()
        {
            return id.get();
        }

        public SimpleIntegerProperty idProperty()
        {
            return id;
        }

        public void setId(int id)
        {
            this.id.set(id);
        }
    }

    public static int BinarySearch(ArrayList<Integer> idList, int id)
    {
        int begin = 0;
        int end = idList.size() - 1;
        while(begin <= end)
        {
            int mid = (begin + end) / 2;
            if(idList.get(mid) > id)
            {
                end = mid - 1;
            }
            else if(idList.get(mid) < id)
            {
                begin = mid + 1;
            }
            else
            {
                return mid;
            }
        }
        return -1;
    }
}


